angular.module('starter')

.controller('CourseListCtrl', function ($scope, $faAPI, $rootScope, $faPopup, $faUser,$state,$stateParams,$faWechat,$http,$faUser,$location) {

    $scope.soldOut = $stateParams.soldOut == 'true'? true : false;//课程下架?
    
    $scope.isLogin = $faUser.info.isLogin;
	//$http({
	//	methods:'get',
	//	url:'/api/login'
	//}).success(function(data){
	//	console.log(data)
	//});
    $scope.reqUrl = reqUrl;
        $scope.page = {
            pageNo: 1,
            PageSize: 5,
            hasNaxtPage: true
        }
        $scope.acList = [];
        var acList = [];
        $scope.tanHide = function () {
            $scope.isLogin = true;
        }
        //登录
        $scope.login = function () {
            //$rootScope.modal.fastLogin();
            if (!$faUser.info.isLogin) {
                $rootScope.modal.login();
                //登录完成之后执行的回调
                window.keCallback = function(){
                    //$scope.isLogin = true;
                    window.location.reload();
                }
            }
        };

        $scope.goKcDetail = function(id){
            $faUser.info.isLogin ? $state.go('kcDetail',{id:id}) : $rootScope.modal.login();
        };
       
        
        $scope.loadMore = function () {
            var pramise = $http({
                method: "GET",
                url: WXJKQZ+'/wjtCourse/listAllWjtCourse',
                params: $scope.page
            });
            pramise.then(function (json) {

                var data = json.data.attribute;

                acList = acList.concat(data.list);
                $scope.acList = acList;

                $scope.page = data.pager;
                $scope.page.pageNo = data.pager.nextPage;
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
            //$faAPI.course.getCounterList($scope.page).then(function (data) {
            //
            //});
        };






        //分享到朋友圈
        $faWechat.api.onMenuShareTimeline({
            title: '金策师-微讲坛', // 分享标题
            imgUrl: '',// 分享图标
            desc:'金策师-微讲坛',
            link:$location.host()+'/#/keList/false',
            success: function() {
                // 用户确认分享后执行的回调函数
            },
            cancel: function() {
                // 用户取消分享后执行的回调函数
            }
        });

        //分享给朋友
        $faWechat.api.onMenuShareAppMessage({
            title: '金策师-微讲坛', // 分享标题
            imgUrl: '' ,// 分享图标
            desc:'金策师-微讲坛',
            link:$location.host()+'/#/keList/false',
            success: function() {
                // 用户确认分享后执行的回调函数
            },
            cancel: function() {
                // 用户取消分享后执行的回调函数
            }
        })



})
.controller('CourseDetailCtrl', function ($scope,$faPopup,$ionicSlideBoxDelegate,$faAPI,$http,$stateParams,$timeout,$faPlatform,$rootScope,$state,$location,$faUser,$faShare,$faWechat) {

    $scope.showWeiXinImg = false;
    $scope.id = $stateParams.id;
    $scope.nowPPTpage = 1;
    $scope.local = reqUrl;
    $scope.isLogin = $faUser.info.isLogin;


    $scope.isCourseStart = true;
    $scope.isWeChat = $faPlatform.weChat;

    var lyAudio = document.getElementById('audioBox'),
        timer = '',
        i = 0;
        t = $stateParams.type || 2 ;//默认不是从列表页面进入详情页面



    //音乐播放结束
    lyAudio.onended = function () {
        $scope.isPlay = false;
        var voilen = $scope.sniInfo[$scope.nowPPTpage-1].wjtCourseAudioList.length;
        if( i < voilen-1 ){
            i++;
            $scope.audioUrl = $scope.local + $scope.sniInfo[$scope.nowPPTpage-1].wjtCourseAudioList[i].audioMediaAddress
            lyAudio.src = $scope.audioUrl;
            lyAudio.onloadstart = function () {
                lyAudio.play();
                $scope.isPlay = true;
                $scope.$apply();
            }
        }else{
            i = 0;
            $scope.playOver = true;
            $scope.$apply($scope.playOver);
            if( $scope.acInfo.coursePageCount > $scope.nowPPTpage ){
                timer = $timeout(function(){
                    $scope.next();
                    $scope.playOver = false;
                },3000)
            }
        }
    };
    function  getDate(){

        var pramise = $http({
            method: "GET",
            url: WXJKQZ+'/wjtCourse/listenWjtCourse',
            params: {id:$scope.id,_pt:'wap',type:t}
        });
        pramise.then(function (json) {
            if (json.data.statusCode === '6007') {
                //alert('课程已下架');
                $state.go('kcList',{soldOut : true});
            } else {

                if (json.data.statusCode === '6009') {
                    $scope.$watch('isLogin', function () {
                        if ($rootScope.isLogin) {
                            getDate();
                        }
                    }, true);
                } else {
                    if (json.data.statusCode === '6006') {
                        $scope.isCourseStart = false;
                        return;
                    }
                    $scope.acInfo = json.data.attribute.dto;
                    $scope.sniInfo = $scope.acInfo.wjtCoursePicList;

                    $scope.audioUrl = $scope.local + $scope.sniInfo[0].wjtCourseAudioList[0].audioMediaAddress;
                    lyAudio.src = $scope.audioUrl;
                    $scope.nowPPtime = $scope.countTime(); //当前ppt音频总时长

                    $scope.share($scope.acInfo);//分享
                }
            }


        })


    }
    getDate();
    //登录完成之后执行的回调
    function keCallback(){
        getDate();
        $scope.isCourseStart = true;
        $scope.isLogin = true;
    }
    //登录
    $scope.login = function () {
        $rootScope.modal.login(keCallback);
    };
    //登录
    $scope.goLogin = function(){
        if (!$faUser.info.isLogin) {
            $rootScope.modal.login(keCallback);
        }
    }
    if( !$scope.isLogin && $scope.isCourseStart ) {
        $scope.goLogin();
    }

    $scope.requestFullScreen = function(){
        var de = document.getElementById('silder');
        if (de.requestFullscreen) {
            de.requestFullscreen();
        } else if (de.mozRequestFullScreen) {
            de.mozRequestFullScreen();
        } else if (de.webkitRequestFullScreen) {
            de.webkitRequestFullScreen();
        }
    };
    //上一页
    $scope.next = function () {
        $timeout.cancel(timer);
        $scope.playOver = false
        $ionicSlideBoxDelegate.next();
    };
    //下一页
    $scope.prev = function () {
        $ionicSlideBoxDelegate.previous();
    };
    //重新播放
    $scope.rePlay = function () {
        $scope.audioUrl = $scope.sniInfo[$scope.nowPPTpage - 1].wjtCourseAudioList[0].audioMediaAddress+"?"+new Date();
        lyAudio.src = $scope.local+$scope.audioUrl;
        lyAudio.onloadstart = function () {
            lyAudio.play();
            $scope.isPlay = true;
            $scope.$apply();
        }
        $timeout.cancel(timer);
        $scope.playOver = false;
    };
    //幻灯片切换
    $scope.slideHasChanged = function(index){
        //$scope.hostUrl = audio[index]
        $scope.audioUrl = $scope.local + $scope.sniInfo[index].wjtCourseAudioList[0].audioMediaAddress;
        lyAudio.src = $scope.audioUrl;
        $scope.nowPPTpage = index + 1;
        $scope.isPlay = false;
        $scope.nowPPtime = $scope.countTime(); //当前ppt音频总时长
        lyAudio.onloadstart = function () {
            lyAudio.play();
            $scope.isPlay = true;
            $scope.$apply();
        }
    };
    //播放暂停
    $scope.audioPlayPause = function(){
        if($scope.isPlay){
            lyAudio.pause();
            $scope.isPlay = false;
        }else{
            lyAudio.play();
            $scope.isPlay = true;

        }
    };

    //统计当前ppt音频总时长
    $scope.countTime = function(){
        var se = 0;
        angular.forEach($scope.sniInfo[$scope.nowPPTpage-1].wjtCourseAudioList,function(data,index){
            se = se + data.audioTimeCount;
        })
        return se;
    }
    //显示微信二维码
    $scope.showWeiXinImg = function(){

        $scope.showWeiXin = !$scope.showWeiXin;

    }
    //分享
    $scope.share = function (obj) {

        var imgUrl = obj.wechatSharePic ? obj.wechatSharePic : obj.lecturersPic;
        //分享到朋友圈
        $faWechat.api.onMenuShareTimeline({
            title: obj.wechatShareTitle || obj.courseTitle, // 分享标题
            imgUrl: $scope.local + imgUrl,// 分享图标
            link:$location.protocol()+'://'+$location.host()+'/#'+$location.path(),
            desc:obj.courseDesc,
            success: function() {
                // 用户确认分享后执行的回调函数
            },
            cancel: function() {
                // 用户取消分享后执行的回调函数
            }
        })
        //分享给朋友
        $faWechat.api.onMenuShareAppMessage({
            title: obj.wechatShareTitle || obj.courseTitle, // 分享标题
            imgUrl: $scope.local + imgUrl ,// 分享图标，
            link:$location.protocol()+'://'+$location.host()+'/#'+$location.path(),
            desc:obj.courseDesc,
            success: function() {
                // 用户确认分享后执行的回调函数
            },
            cancel: function() {
                // 用户取消分享后执行的回调函数
            }
        })
    }


})
.controller('drainListCtrl',function($scope,$faAPI,$stateParams,$location,$filter,$faWechat,$anchorScroll,$http){
  if(!$stateParams.id){
      return
  }
  $scope.data = {
      activitiesHostPartnerId:$stateParams.id,
      pageNo:1,
      pageSize:3
  };
  $scope.lists = [];
  $scope.hasNaxtPage = true;
  $scope.hostImgUrl = reqUrl;

  $scope.loadMoreActivity = function(){
      var premise = $http({
          method: "GET",
          url: WXJKQZ+'/wjtPublicActivities/listWjtPublicActivities',
          params: $scope.data
      })
      premise.then(function(resp){
          $scope.lists = $scope.lists.concat(resp.data.attribute.list);
          $scope.data.pageNo= resp.data.attribute.pager.nextPage;
          $scope.hasNaxtPage = resp.data.attribute.pager.hasNaxtPage;

          $scope.$broadcast('scroll.infiniteScrollComplete');
      })

  }
  // $scope.$on("$ionicView.enter", function() {
  //   //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
  // });
  //$faWechat.api.onMenuShareTimeline({
  //    title: '这里有很多适合理财师的活动，公开课，读书会等等一系列的活动都在这里，我们还有更多的活动正在准备中！', // 分享标题
  //    link: '', // 分享链接
  //    imgUrl: 'http://static.superfa.cn/upload/bann/20150922/1442901612479pic.jpg', // 分享图标
  //    success: function() {
  //        // 用户确认分享后执行的回调函数
  //    },
  //    cancel: function() {
  //        // 用户取消分享后执行的回调函数
  //    }
  //});
  //
  //$faWechat.api.onMenuShareAppMessage({
  //    title: '又有理财师的福利了，神秘活动等你来！', // 分享标题
  //    desc: '这里有很多适合理财师的活动，公开课，读书会等等一系列的活动都在这里，我们还有更多的活动正在准备中！', // 分享描述
  //    link: '', // 分享链接
  //    imgUrl: 'http://static.superfa.cn/upload/bann/20150922/1442901612479pic.jpg', // 分享图标
  //    type: '', // 分享类型,music、video或link，不填默认为link
  //    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
  //    success: function() {
  //        // 用户确认分享后执行的回调函数
  //    },
  //    cancel: function() {
  //        // 用户取消分享后执行的回调函数
  //    }
  //});
})
.controller('rankIndexCtrl',function($scope,$faAPI,$rootScope,$state,$faUser,$faUtil,$timeout,$lfShare){

    $scope.reqData = {};
    $scope.islogin = false;
    //vistDate=true  代表增量---true 不传是累积排行榜
    $faAPI.activity.shopVistSort().then(function(json){
        $scope.resData = json.list;
    });

    var phone  = window.localStorage.getItem("rankPhone");

    function getmydata(){
        //通过检查本地的手机号，判断是否登录
        phone  = window.localStorage.getItem("rankPhone")
        if (phone) {
            //自己店铺排名
            $faAPI.activity.shopUserVistSort({
                shopId: phone,
                vistDate: true
            }).then(function (json) {
                $scope.myresData = json.dto;
                $scope.zengliang = json.zengliang;
                $scope.islogin = true;

            });

        }else {
            $scope.islogin = false;
        }

    }
    getmydata();
    //手动退出登录
    //window.localStorage.removeItem('rankPhone');
    //彩蛋开启时间
    $faAPI.activity.getActivityTime().then(function(json){
        $scope.timeData = json.dto;
    });
    function loginCallback(phone){
        console.log(phone);
        console.log('logincallback');
        window.localStorage.setItem("rankPhone", phone);
        //window.location.href = location.href+'?time='+((new Date()).getTime());
        getmydata();
    }
    $scope.gomyshop = function(){
        console.log($scope.islogin);
        //
        if($scope.islogin == false){
            $rootScope.modal.fastLogin(loginCallback)
        }else {
            $state.go('shopPreview',{sphone:phone});
        }
    };
    //微信分享
    var shareData = {
        title:'[金策师]社交达人排行榜',
        desc:'装修理财师个性店铺，冲刺大奖，1999元现金等你拿~',
        link:'http://m.jincs.cn/#/rankIndex',
        imgUrl:'http://lec.superfa.cn/upload/bann/20171016/advertImage_1508133010251.png'
    };
    $lfShare.wechatShare(shareData);


})
.controller('eggrankCtrl',function($scope,$faAPI){
    //vistDate=true  代表增量---true 不传是累积排行榜
    $faAPI.activity.shopVistSort({
        vistDate:true
    }).then(function(json){
        $scope.resData = json.list;
    });
})

.controller('customerCtrl',function($scope,$faAPI,$http,$faPopup,$stateParams,$faPlatform,$state, $faUser) {


    //cSex: [{
    //  key: '1',
    //  name: '男'
    //}, {
    //  key: '2',
    //  name: '女'
    //}],
    //初始化数据
    $scope.initialize = function () {
        $scope.isSuccess = false;
        $scope.successNum = false;
        $scope.customerPhone = $stateParams.phone;
        $scope.data = {};
        $scope.data.qajson = [];

        $scope.step = 1;

        $scope.buttonText = '下一题';

        //self.data.cSex = self.cSex[0];


        $faAPI.allin.listFpShopSubject().then(function(json) {
          $scope.questionList = json.list;
            console.log($scope.questionList);
        });


    };
    $scope.initialize();
  /*  $scope.bodaPhone =function() {
        console.log($stateParams)
        if ($faPlatform.IOSAPP) {
            //IOS拨打电话
            phonedialer.dial($stateParams.phone, function (err) {
                if (err == "feature")
                    console.info("Your device doesn't support this feature.");
                if (err == "empty")
                    console.info("Unknown phone number");
            });
        } else {
            //ANDROID拨打电话
            window.location.href = "tel:"+$stateParams.phone;
        }
    }*/
    //选择答案

    $scope.change = function (index,id,answer) {
            console.log(index,id,answer);
            var self = this;
            self.data.qajson[index] = {
                tid: id,
                sid: answer
            };
            console.log(self.data.qajson);

    };
    //提交答题
    $scope.customerdone = function () {

        var self = this;

        if (self.step - 1 >= 0 && !self.data.qajson[self.step - 1]) {
            $faPopup.alert({
                title: '请做出选择'
            })
        } else if (self.step < $scope.questionList.length) {
            self.step++;
            if (self.step > $scope.questionList.length - 1) {
                self.buttonText = '提交评估';
            } else {
                self.buttonText = '下一题';
            }
        } else {

            var  qajson = angular.toJson(self.data.qajson);
            $faAPI.customer.addFpShopSubjectUser({
                'qajson':angular.toJson(self.data.qajson)
            }).then(function(json) {
                console.log(json);
                var data = json;

                if (data.trueNum >= 4) {
                    $scope.isSuccess = true;

                    //答题通过 - 更新用户状态
                    $faUser.update();
                } else {
                    $scope.successNum = true;
                    $scope.successNum2 = data.trueNum;
                }

            })
            //$faAPI.customer.add(self.data).then(function(json) {
            //
            //  $state.go('customer.detail', {
            //    id: json.id
            //  });
            //
            //  self.hide();
            //
            //});
        }

        //}

    }
    //重新答题
    $scope.again = function(){
        $scope.initialize();
    }

    //跳转到盟友
    $scope.toMY = function () {
        //调用原生跳转
        if($faPlatform.IOSAPP) {

        } else {

        }
    }
});
